package cn.easyplatform.studio.cmd.importAll;

import cn.easyplatform.studio.StudioException;
import cn.easyplatform.studio.dao.DaoException;
import cn.easyplatform.studio.interceptor.Command;
import cn.easyplatform.studio.interceptor.CommandContext;
import cn.easyplatform.studio.vos.MenuInfoVo;

import java.util.ArrayList;
import java.util.List;

public class SaveMenuInfoCmd implements Command<Boolean> {
    private List<MenuInfoVo> voList;
    private List<MenuInfoVo> updateMenuInfoVos = new ArrayList<>();
    private List<MenuInfoVo> addMenuInfoVos = new ArrayList<>();
    public SaveMenuInfoCmd(List<MenuInfoVo> voList) {
        this.voList = voList;
    }
    @Override
    public Boolean execute(CommandContext cc) {
        List<MenuInfoVo> list = cc.getMenuInfoDao(null).selectAllList();
        List<String> menuInfoKeyList = new ArrayList<>();
        for (MenuInfoVo vo: list) {
            menuInfoKeyList.add(vo.getMenuId());
        }

        parseData(voList, menuInfoKeyList);

        try {
            cc.beginTx();
            cc.getMenuInfoDao(null).setMenuList(addMenuInfoVos);
            cc.getMenuInfoDao(null).updateMenuList(updateMenuInfoVos);
            cc.commitTx();
        } catch (Exception ex) {
            cc.rollbackTx();
            if (ex instanceof DaoException)
                throw (DaoException) ex;
            throw new StudioException("ExportCmd:" + ex.getMessage());
        } finally {
            cc.closeTx();
        }
        return Boolean.TRUE;
    }

    private void parseData(List<MenuInfoVo> vos, List<String> allDicVoList) {
        for (MenuInfoVo vo: vos) {
            if (allDicVoList.contains(vo.getMenuId()))
                updateMenuInfoVos.add(vo);
            else
                addMenuInfoVos.add(vo);

            if (vo.getChildrenList() != null && vo.getChildrenList().size() > 0)
                parseData(vo.getChildrenList(), allDicVoList);
        }
    }
}
